package com.qst.survey.controller;

import com.qst.survey.entity.Admin;
import com.qst.survey.pojo.Result;
import com.qst.survey.pojo.StatusCode;
import com.qst.survey.service.AdminService;
import com.qst.survey.util.JwtUtil;
import com.qst.survey.util.NoAuthorization;
import com.qst.survey.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author ：Ariel~~
 * @description： 管理员控制类
 * @date ：2020/12/27 16:09
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {

    @Autowired
    AdminService adminService;
    @Autowired
    RedisUtils redisUtils;

    /**
     * @param admin
     * @return com.qst.survey.pojo.Result
     * @description: TODO 管理员登录
     * @date 2021/4/2
     */
    @NoAuthorization
    @PostMapping("/login")
    public Result Login(@RequestBody Admin admin, HttpServletRequest request) {
        Admin admin1 = adminService.loginAdmin(admin);
        if (admin1!=null) {
            //密码是正确的
            //生成JWT令牌,返回到客户端
            Map<String, Object> info = new HashMap<>();
            info.put("username", admin.getUsername());
            info.put("Password", admin.getPassword());
            //基于工具类生产的jwt令牌
            String jwt = JwtUtil.createJwt(admin1.getUsername(), request.getRemoteAddr(), null);
            info.put("token", jwt);
            String token = null;
            try {

                token = redisUtils.getToken(admin1.getUsername());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (token != null) {
                redisUtils.delete(admin1.getUsername());
            }
            redisUtils.setToken(admin1.getUsername(), jwt);
            return new Result(true, StatusCode.OK, "登录成功", info);
        } else {
            return new Result(false, StatusCode.ERROR, "登录失败!");
        }
    }

    /**
     * @param admin
     * @return com.qst.survey.pojo.Result
     * @description TODO  管理员注册
     * @date 2021/4/2
     */
    @NoAuthorization
    @PostMapping("/register")
    public Result register(@RequestBody Admin admin) {
        adminService.addAdmin(admin);
        return new Result(true, StatusCode.OK, "提交成功!");
    }
}
